﻿using System;
using System.IO;
using System.Threading;

namespace BGM.Sensors.MeasuringDevice
{
    internal class StreamPort : IPort
    {
        private Stream currentStream;
        private bool isOpen;
        private Thread readerThread;
        private string data = string.Empty;
        public StreamPort(Stream stream)
        {
            this.currentStream = stream;
            this.isOpen = false;
        }


        private void reader()
        {
            while (isOpen)
            {
                try
                {
                    byte[] tmp = new byte[1];


                    if (currentStream.Read(tmp, 0, 1) > 0 && tmp.Length != 0)
                    {
                        lock (this)
                        {
                            data += (char)tmp[0];

                        }
                        OnDataRecieved();
                        continue;
                    }
                    Thread.Sleep(100);
                }
                catch (Exception)
                {


                }

            }
        }

        private void OnDataRecieved()
        {
            EventHandler handler = DataReceived;
            if (handler != null)
                handler(this, new EventArgs());
        }

        #region IPort Members

        public void Open()
        {
            lock (this)
            {

                isOpen = true;
            }
            readerThread = new Thread(new ThreadStart(reader));
            readerThread.Start();

        }

        public void Close()
        {
            lock (this)
                isOpen = false;
        }

        public string ReadExisting()
        {
            string tmp;
            lock (this)
            {
                tmp = data;
                data = string.Empty;
            }
            return tmp;
        }

        public void Write(string s)
        {
            foreach (var item in s.ToCharArray())
            {
                currentStream.Write(new byte[] { (byte)item }, 0, 1);
                //currentStream.WriteByte((byte)item);
                //currentStream.Flush();
            }

            //for (int i = 0; i < 20; i++)
            //{
            //    currentStream.Write(new byte[] { 0x5 }, 0, 1);
            //    Thread.Sleep(3000);
            //}
            //TextWriter writer = new StreamWriter(currentStream);
            //writer.Write(s);
        }

        public bool IsOpen
        {
            get { return isOpen; }
        }

        public event EventHandler DataReceived;
        public bool DtrEnable
        {
            set { }
        }

        public bool RtsEnable
        {
            set { }
        }
        #endregion

       

       

    }
}
